<?php

namespace app\controller\merchant;

use app\BaseController;
use app\model\StationBalanceNotice;
use app\model\SupplierBalanceNotice;
use app\model\UserBalanceDetail;
use think\response\Json;

class Order extends BaseController
{
    public function confirm(): Json
    {
        return $this->handle(function () {
            $param = $this->request->post();
            $merchant = $this->request->account;
            $model = new \app\model\Order;
            $order = $model->where('order_sn', $param['order_sn'])->where('gas_id', $merchant['station_id'])->find();
            if (empty($order)) throw new \Exception('订单不存在');
            if ($order['state'] != 7) throw new \Exception('订单状态错误');
            $order->state = 3;
            $order->supplier = $merchant['id'];
            $order->confirm_date = date("Y-m-d H:i:s");
            $user = $this->app->make(\app\model\User::class)->where('id', $order['account'])->find();
            //这里需要扣三次款，分别是用户、机构和平台
            //平台扣款金额为本次加油金额的默认折扣金额，用户和机构扣款金额为本次实际支付金额
            //本次加油类型
            $oil = $this->app->make(\app\model\StationOilNumber::class)->where('name', $order['oil_type'])->value("id");
            //获取油站优惠金额
            $discount = $this->app->make(\app\model\StationPrice::class)->where('station_id', $merchant['station_id'])->where('oil_id', $oil)->where('sup_id', 0)->find();
            //计算本次油站扣款金额
//            $discount = (float)bcmul($discount['discount_price'], $order['number'], 2);
            $stations = $this->app->make(\app\model\StationBasic::class)->where('id', $merchant['station_id'])->find();
            //获取油站当前余额
            $stationBalance = $stations['balance'];
            if ($stationBalance < $order['money']) throw new \Exception("油站余额不足");
            $model->startTrans();
            $order->save();
            $stations->dec("balance", $order['money'])->save();
            $user->dec("freeze_balance", $order['amount'])->save();
            $this->app->make(UserBalanceDetail::class)->save([
                "number" => $order['order_sn'],
                "money" => $order['amount'],
                "old_money" => bcadd($order['amount'], $user['balance'], 2),
                "new_money" => $user['balance'],
                "type" => 3,
                "tag" => 2,
                "remark" => "{$merchant['station']['name']}加油订单",
                "uid" => $order['account']
            ]);
            $supplier = $this->app->make(\app\model\Supplier::class)->where('id', $user['supplier'])->find();
            if(!empty($supplier)){
                $total = bcadd($supplier['balance'],$supplier['forzen_balance'],2);
                $supplier->dec("forzen_balance", $order['amount'])->inc("account_balance", $order['amount'])->save();
                $this->app->make(SupplierBalanceNotice::class)->save([
                    "sid" => $supplier['id'],
                    "money" => $order['amount'],
                    "amount" => $total,
                    "total" => (float)bcsub($total,$order['amount'],2),
                    "type" => 3,
                    "tag" => 2,
                    "remark" => "{$merchant['station']['name']}加油订单",
                    "order_sn" => $order['order_sn']
                ]);
            }
            $model->commit();
            return $order->toArray();
        });
    }

    public function lst(): Json
    {
        return $this->handle(function () {
            $merchant = $this->request->account;
            $model = new \app\model\Order;
            $param = $this->request->param();
            $lst = $model->where('gas_id', $merchant['station_id'])->when(!isset($param['state']), function ($query) use ($param) {
                if (empty($param['state'])) $query->whereIn('state', [3, 4, 5]);
                else $query->where('state', $param['state']);
            })->where('supplier', $merchant['id'])->order('create_time desc')->paginate();
            return $lst->toArray();
        });
    }

    public function index(): Json
    {
        return $this->handle(function () {
            $merchant = $this->request->account;
            $model = new \app\model\Order;
            $param = $this->request->param();
            $lst = $model->where('gas_id', $merchant['station_id'])->when(!isset($param['state']), function ($query) use ($param) {
                if (empty($param['state'])) $query->whereIn('state', [3, 4, 5]);
                else $query->where('state', $param['state']);
            })->where('supplier', $merchant['id'])->order('create_time desc')->limit(2)->select();
            return $lst->toArray();
        });
    }

    public function detail(): Json
    {
        return $this->handle(function () {
            $id = $this->request->param('id');
            return $this->app->make(\app\model\Order::class)->with(['station', 'confirm'])->where('id', $id)->find();
        });
    }
}
